package com.z.blog.controller;

import com.github.pagehelper.PageInfo;
import com.z.admin.entity.UploadFiles;
import com.z.base.vo.PageVo;
import com.z.base.vo.Result;
import com.z.base.web.BaseController;
import com.z.blog.entity.Message;
import com.z.blog.service.IMessageService;
import com.z.utils.ImageBase64Converter;
import com.z.utils.KitFileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 留言Controller
 *
 * @author z
 * @date 2022-09-13
 */
@Controller
@RequestMapping("/blog/message")
public class MessageController extends BaseController {

    @Autowired
    private IMessageService messageService;

    /**
     * 查询留言列表
     */
    @ResponseBody
    @GetMapping("/data")
    public Result list(@ModelAttribute Message message, PageVo pageVo) {
        PageInfo<Message> pageInfo = messageService.selectMessagePage(message, pageVo);
        pageInfo.getList().forEach(o -> o.setImage(ImageBase64Converter.convertFileToBase64(o.getImage())));
        return Result.table(pageInfo);
    }

    /**
     * 新增留言
     */
    @ResponseBody
    @PostMapping("/save")
    public Result save(@RequestBody Message message) {
        message.setCreateTime(new Date());
        return Result.decide(messageService.save(message));
    }

    @PostMapping(value = "/uploadImg")
    @ResponseBody
    public Object uploadImg(@RequestParam("layuiFile") MultipartFile[] layuiFile, HttpServletRequest request, HttpServletResponse response){
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> map2=new HashMap<>();
        KitFileUtil kitFileUtil=new KitFileUtil();
        map = kitFileUtil.upload(layuiFile, request, response, "front/");
        String error = map.get("error").toString();
        if("101".equals(error)){
            return Result.error((String)map.get("message"));
        }
        map2.put("error",0);
        String url[]=(String[])map.get("url");
        map2.put("url",url[0]);
        UploadFiles file = new UploadFiles();
        file.setName((String)map.get("fileName"));
        file.setUrl(url[0]);
        file.setCreateTime(new Date());
        file.setType("tp");
        return Result.success(map2);
    }

}
